<template>
  <div class="login-container">
    <div class="login-wrap">
      <div class="cover" :style="$store.state.user.loginPic | coverImg"></div>
      <div class="login-form">
        <template v-if="loginTypes.includes('account') && loginWay === 'account'">
          <h2 class="login-type">{{ $t('modules.user.loginByAccount') }}</h2>
          <!-- hid 登录 -->
          <div v-if="isHid" class="hid-wrap">
            <a-spin :spinning="loginHid">
              <h3 class="hid-tips">{{ hidFocused ? '等待刷卡' : '无效区域' }}</h3>
              <div>
                <img
                  :src="require('@/assets/images/layout/auth/hid.png')"
                  width="122"
                  height="109"
                  alt="hid"
                  @click="$refs.hid.focus()"
                />
              </div>
              <div class="hid-input">
                <a-input v-model="hidNo" ref="hid" @blur="hidFocused = false" @focus="hidFocused = true" />
              </div>
            </a-spin>
          </div>
          <!-- 账户密码登录 -->
          <a-form v-else id="formLogin" ref="formLogin" :form="form" @submit="handleSubmit">
            <a-form-item>
              <a-input
                size="large"
                type="text"
                :placeholder="$t('common.account')"
                v-decorator="[
                  'username',
                  {
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: $t('common.emptyErr', { name: $t('common.account') })
                      }
                    ],
                    validateTrigger: 'change'
                  }
                ]"
              >
                <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-form-item>

            <a-form-item>
              <a-input
                size="large"
                type="password"
                autocomplete="off"
                :placeholder="$t('common.password')"
                v-decorator="[
                  'password',
                  {
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: $t('common.emptyErr', { name: $t('common.password') })
                      }
                    ],
                    validateTrigger: 'blur'
                  }
                ]"
              >
                <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-form-item>

            <a-form-item style="margin-top: 40px;">
              <a-button
                size="large"
                type="primary"
                htmlType="submit"
                class="login-button"
                :loading="loginBtn"
                :disabled="form | accountActive"
              >{{ $t('common.ok') }}</a-button
              >
            </a-form-item>
          </a-form>
          <div class="user-login-other" v-if="loginTypes.includes('hid')">
            <span>{{ $t('modules.user.otherLoginMethod') }}</span>
            <a href="javascript:;" @click="isHid = !isHid">
              {{ isHid ? $t('platformManagement.app.loginByAccount') : $t('platformManagement.app.loginByHid') }}
            </a>
          </div>
        </template>
        <div class="exchange" v-if="loginTypes.some(item => ['wechat', 'dingtalk'].includes(item))" @click="toggleScan">
          <a-icon :type="loginWay === 'scan' ? 'rollback' : 'scan'" />
        </div>
        <!-- 企业微信登录 -->
        <div v-show="loginWay === 'scan'">
          <div id="wechatQR" v-if="loginTypes.includes('wechat')"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { login, loginByHid, readConfig, readLoginPageWays } from '@/api/auth'
import { rootURL } from '@/config/api.config'
import MD5 from 'md5'
import debounce from 'lodash.debounce'
import { getQueryParameters } from '@/utils/util'

export default {
  name: 'Login',
  data () {
    return {
      loginTypes: ['account'],
      loginBtn: false,
      form: this.$form.createForm(this),
      WwJDKLoaded: false,
      loginWay: 'account',
      // hid 登录
      isHid: false,
      hidNo: '',
      hidFocused: false,
      loginHid: false,
      // 扫码登录
      openChat: {}
    }
  },
  filters: {
    coverImg (url) {
      return `background-image: url(${rootURL}${url});background-color: #ccc;`
    },
    accountActive (form) {
      const { getFieldValue } = form
      return !(getFieldValue('username') && getFieldValue('username').trim() && getFieldValue('password'))
    }
  },
  watch: {
    hidNo (val) {
      if (val) this.handleHidSubmit()
    },
    isHid (val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs.hid.focus()
        })
      }
    }
  },
  mounted () {
    this.getPageInfo()
    // 扫码失败返回
    const { error } = this.$route.query
    const message = decodeURIComponent(error)
    if (error) {
      this.$notification.error({
        message: this.$t('common.error'),
        description: message || '系统错误，请联系管理员'
      })
      this.$router.replace({ path: '/login' })
    }
  },
  methods: {
    ...mapActions(['Login', 'LoginByHid']),
    // 获取企业信息配置和登录方式
    async getPageInfo () {
      // 企业信息
      const basicInfo = await readConfig()
      const { logoPic, loginPic, name, iconPic, url, code } = basicInfo.data
      if (basicInfo.code === 'sso.ok') {
        this.$store.dispatch('setLoginConfig', {
          loginPic,
          iconPic,
          logoPic,
          url,
          code
        })
      }
      // 登录方式
      const loginTypes = await readLoginPageWays()
      if (loginTypes.code === 'sso.ok') {
        this.loginTypes = loginTypes.data.ways || ['account']
        this.openChat = loginTypes.data.openChat || {}
      }
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        Login
      } = this

      this.loginBtn = true

      const validateFieldsKey = ['username', 'password']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values, password: MD5(values.password) }

          Login(loginParams)
            .then(res => this.loginSuccess(res))
            .finally(() => {
              this.loginBtn = false
            })
        } else {
          setTimeout(() => {
            this.loginBtn = false
          }, 600)
        }
      })
    },
    // hid 卡登录
    handleHidSubmit: debounce(async function () {
      this.loginHid = true
      const req = {
        hidNo: this.hidNo
      }
      this.LoginByHid(req)
        .then(res => this.loginSuccess(res))
        .catch(() => {
          this.hidNo = ''
        })
        .finally(() => {
          this.loginHid = false
        })
    }, 200),
    loginSuccess (res) {
      // 获取url上的参数
      const options = getQueryParameters()
      const redirect = this.$route.query.redirect || '/dashboard'
      if (options.redirect) {
        // 如果是从其他项目跳转过来的
        window.location.href = `${options.redirect}?token=${res}`
      } else {
        this.$router.push({ path: redirect })
      }
    },
    // 切换扫码方式
    async toggleScan () {
      this.loginWay = this.loginWay === 'scan' ? 'account' : 'scan'
      if (this.loginWay === 'scan') {
        if (this.loginTypes.includes('wechat')) {
          if (!this.WwJDKLoaded) {
            await require('@/assets/js/wwLogin-1.0.0')
            this.WwJDKLoaded = true
            const { agentId, corpId, secretId } = this.openChat
            const redirect_uri = this.$store.state.user.url + '/api/wx/callback'
            window.WwLogin({
              id: 'wechatQR',
              appid: corpId,
              agentid: agentId,
              redirect_uri,
              state: '',
              href: ''
            })
          }
        } else {
          // 钉钉
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  display: flex;
  height: 100%;
  width: 100%;
  justify-content: center;
  align-items: center;

  .login-wrap {
    flex: 0 0 1135px;
    height: 100%;
    max-height: 600px;
    display: flex;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    background-color: #fff;

    .cover {
      flex: 1;
      background-repeat: no-repeat;
      background-position: center;
      background-size: cover;
    }

    .login-form {
      position: relative;
      padding: 60px 80px;
      width: 460px;

      .login-type {
        font-size: 18px;
        font-weight: 400;
        margin-bottom: 48px;
        padding-bottom: 12px;
        border-bottom: 2px solid #ccc;
      }
      .exchange {
        position: absolute;
        width: 65px;
        height: 65px;
        top: 60px;
        right: 0;
        transform: translatex(50%);
        line-height: 65px;
        text-align: center;
        font-size: 40px;
        color: #fff;
        background-color: #3ac386;
        cursor: pointer;
      }

      button.login-button {
        padding: 0 15px;
        font-size: 16px;
        height: 40px;
        width: 100%;
      }

      .user-login-other {
        text-align: left;
        margin-top: 24px;
        line-height: 22px;

        .item-icon {
          font-size: 24px;
          color: rgba(0, 0, 0, 0.2);
          margin-left: 16px;
          vertical-align: middle;
          cursor: pointer;
          transition: color 0.3s;

          &:hover {
            color: #1890ff;
          }
        }
      }
    }
  }

  .hid-wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 186px;
    user-select: none;

    .hid-tips {
      margin-bottom: 8px;
      text-align: center;
    }

    .hid-input {
      width: 0;
      height: 0;
      opacity: 0;
    }
  }
}
#wechatQR {
  width: 300px;
  height: 400px;
}
</style>
